package xh;

import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/7/6.
 */
public class FileListManager {

    HashMap<String, FileInfo> fileList = new HashMap<String, FileInfo>();

    ScheduledExecutorService broadcastMyFilesSchedule;

    FileIdGenerator fileIdGenerator = new FileIdGenerator();

    public void start() {

        broadcastMyFilesSchedule = Executors.newSingleThreadScheduledExecutor();

        broadcastMyFilesSchedule.scheduleAtFixedRate(new BroadCastMyFileTask(), 10, 30, TimeUnit.SECONDS);
    }

    public String getFileName(String fileId) {

        synchronized (fileList) {
            FileInfo fileInfo = fileList.get(fileId);
            if (fileInfo == null) {
                return null;
            }

            if (fileInfo.isLocal()) {
                return fileInfo.fileName;
            } else {
                return null;
            }

        }
    }

    public void reloadFileListNow() {
        new BroadCastMyFileTask().run();
    }

    public void receiveFileIds(List<String> ids, String remoteIp) {

        synchronized (fileList) {
            for (String id : ids) {

                FileInfo fileInfo = fileList.get(id);
                if (fileInfo == null) {
                    fileInfo = new FileInfo(id, null);
                    fileInfo.remoteIps = new TreeSet<String>();
                    fileInfo.remoteIps.add(remoteIp);
                    fileList.put(id, fileInfo);
                } else {
                    if (!fileInfo.isLocal()) {
                        fileInfo.remoteIps.add(remoteIp);
                    }
                }
            }
        }
    }


    public List<FileInfo> allRemoteFiles() {
        List<FileInfo> result = new ArrayList<FileInfo>();

        synchronized (fileList) {
            for (String k : fileList.keySet()) {
                FileInfo fileInfo = fileList.get(k);
                if (!fileInfo.isLocal()) {
                    result.add(fileInfo);
                }
            }
        }

        return result;
    }


    private class BroadCastMyFileTask implements Runnable {

        public void run() {

            File dir = new File(Global.BasePath);
            List<FileInfo> localFiles = new ArrayList<FileInfo>();
            if (dir != null) {
                for (File f : dir.listFiles()) {

                    if (Global.isDownloadingFile(f.getName())) {
                        continue;
                    }

                    String fileId = fileIdGenerator.generate(f);

                    FileInfo fileInfo = new FileInfo(fileId, f.getName());
                    fileInfo.remoteIps = null;

                    localFiles.add(fileInfo);
                }
            }

            Set<String> localSet = new HashSet<String>();
            synchronized (fileList) {

                for (FileInfo f : localFiles) {
                    fileList.put(f.fileId, f);
                    localSet.add(f.fileId);
                }

                List<String> localDeleted = new ArrayList<String>();
                for (String k : fileList.keySet()) {
                    FileInfo fileInfo = fileList.get(k);
                    if (fileInfo.isLocal() && !localSet.contains(fileInfo.fileId)) {
                        localDeleted.add(k);
                    }
                }

                for (String del : localDeleted) {
                    fileList.remove(del);
                }
            }

            String sendContent = "";
            for (String s : localSet) {
                if (sendContent != "") {
                    sendContent += "###";
                }
                sendContent += s;
            }


            DatagramSocket client = null;
            try {
                client = new DatagramSocket();
//                InetAddress addr = InetAddress.getByName("255.255.255.255");
                InetAddress addr = InetAddress.getByName("192.168.3.112");

                byte[] bytes = sendContent.getBytes("utf-8");
                DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, addr, Global.FileListUdpPort);

                client.send(sendPacket);

            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (client != null) {
                    client.close();
                }
            }

        }
    }

    public static class FileInfo {

        String fileName;

        String fileId;

        // if null, local
        TreeSet<String> remoteIps;

        public FileInfo(String fileId, String fileName) {
            this.fileId = fileId;
            this.fileName = fileName;
        }

        boolean isLocal() {
            return remoteIps == null;
        }
    }
}
